import os
import sqlite3
from flask import Flask, request, abort, make_response, send_file, jsonify, redirect, Blueprint
from flask_jwt_extended import jwt_required, get_jwt
import hashlib
from xml.etree import ElementTree as ET
import sys
import json
import requests
import time
import datetime
import exts
from wechatpy import parse_message
from wechatpy.replies import TextReply, ImageReply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
import random

gongzhonghao_blueprint = Blueprint('gongzhonghao', __name__)

# 这是一条测试提交的批注
# 这是一条测试提交的批注

##############################该段讲述前端如何发送json数据################################
#  要发送的 JSON 数据
# const jsonData = {
#     name: 'John',
#     age: 30,
#     email: 'john@example.com'
# };

#  设置请求选项
# const requestOptions = {
#     method: 'POST',
#     headers: {
#         'Content-Type': 'application/json'
#     },
#     body: JSON.stringify(jsonData)
# };

#  发送请求
# fetch('/process_json', requestOptions)
#     .then(response => {
#         if (!response.ok) {
#             throw new Error('Network response was not ok');
#         }
#         return response.json();
#     })
#     .then(data => {
#         console.log('Server response:', data);
#     })
#     .catch(error => {
#         console.error('There was a problem with the request:', error);
#     });
#####################################################################################

####################### 接口列表（部分）#######################################
# # 尝试获取token
# @gongzhonghao_blueprint.route('/get_wechat_token', methods=['GET'])
# # 创建标签
# @gongzhonghao_blueprint.route('/create_wechat_tag', methods=['POST'])
# # 获取标签
# @gongzhonghao_blueprint.route('/get_wechat_tags', methods=['GET'])
# # 编辑标签
# @gongzhonghao_blueprint.route('/edit_wechat_tag', methods=['POST'])
# # 删除标签
# @gongzhonghao_blueprint.route('/delete_wechat_tag', methods=['POST'])
# # 获取标签下粉丝列表
# @gongzhonghao_blueprint.route('/getall_wechat_tag', methods=['POST'])
# # 批量为用户打标签  （最多20个标签）
# @gongzhonghao_blueprint.route('/batch_wechat_tag', methods=['POST'])
# # 批量为用户取消标签
# @gongzhonghao_blueprint.route('/batchdelete_wechat_tag', methods=['POST'])
# # 获取用户身上的标签列表
# @gongzhonghao_blueprint.route('/getlabel_wechat_tag', methods=['POST'])
#######################################################################


WECHAT_TOKEN = "huixue"
# 全局变量用于存储 token
access_token = ""
expires_time = 0


# gaccessToken = myrequest.Basic().get_access_token()
# gtime = datetime.datetime.now().strftime('%H_%M')


# 测试成功运行代码（不要动！！！！）
@gongzhonghao_blueprint.route('/test', methods=['GET', 'POST'])
def test():
    return f'Hell222o, World!{os.path.abspath(__file__)}'


# 测试用的
# @gongzhonghao_blueprint.route('/test', methods=['POST'])
# def test():
#     # 从请求中获取JSON数据
#     request_data = request.json

#     # 获取access_token
#     access_token = request_data.get('access_token')  # 使用.get方法从JSON数据中获取access_token字段的值

#     return jsonify(access_token=access_token)  # 将获取到的access_token作为JSON数据返回给客户端


# 尝试获取token
@gongzhonghao_blueprint.route('/get_wechat_token', methods=['GET'])
@jwt_required()
def get_wechat_token():
    global access_token  # 使用全局变量
    # 给吴燕使用的账号密码
    appid = "wxad55c42c5def12db"
    appsecret = "4c432ccecfcab9739cc402ccd6fce302"

    # 测试服务器的账号密码
    # appid = 'wxd7173377cb0fefaf'
    # appsecret = '8c5921b88fb379a7a50c45c93d08df48'

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}"

    try:
        # 发送HTTPS GET请求获取token
        response = requests.get(url)
        data = response.json()

        # 检查响应是否成功
        if 'access_token' in data:
            access_token = data['access_token']
            # 返回token
            return jsonify({'access_token': access_token})
        else:
            print(data)
            # 如果获取失败，返回错误信息
            return jsonify({'error': 'Failed to get access token'})

    except Exception as e:
        # 如果发生异常，返回错误信息
        return jsonify({'error': str(e)})


# 尝试获取不同账号token（新）
@gongzhonghao_blueprint.route('/getall_wechat_token', methods=['POST'])
@jwt_required()
def getall_wechat_token():
    try:
        global access_token  # 使用全局变量
        # 给吴燕使用的账号密码
        default_appid = "wxad55c42c5def12db"
        default_appsecret = "4c432ccecfcab9739cc402ccd6fce302"
        # 测试代码
        # default_appid = "11"
        # default_appsecret = "22"
        # 从请求中获取JSON数据
        request_data = request.json

        # 获取appid,appsecret
        appid = request_data.get('appid', default_appid)
        appsecret = request_data.get('appsecret', default_appsecret)

        if (appid == "11" and appsecret == "22"):
            return "测试成功"

        # 构建请求URL
        url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}"

        try:
            # 发送HTTPS GET请求获取token
            response = requests.get(url)
            data = response.json()

            # 检查响应是否成功
            if 'access_token' in data:
                access_token = data['access_token']
                # 返回token
                return jsonify({'access_token': access_token})
            else:
                # 如果获取失败，返回错误信息
                return jsonify({'error': 'Failed to get access token'})

        except Exception as e:
            # 如果发生异常，返回错误信息
            return jsonify({'error': str(e)})
    except Exception as e:
        return redirect('/get_wechat_token')


#获取用户列表GET
@gongzhonghao_blueprint.route('/getUserget', methods=['GET'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'J')
def getUserget():
    global access_token

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={access_token}"

    response = requests.get(url)
    data = response.json()

    return data


# #获取用户列表post
# @gongzhonghao_blueprint.route('/getUserpost', methods=['POST'])
# def getUserpost():

#     #     # 从请求中获取JSON数据
#     request_data = request.json

# #     # 获取access_token
#     access_token = request_data.get('access_token')

#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={access_token}"

#     response = requests.get(url)
#     data = response.json()

#     return data

#获取用户列表post
@gongzhonghao_blueprint.route('/getUserpost', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'J')
def getUserpost():
    # 从请求中获取JSON数据
    request_data = request.json

    # 获取access_token
    access_token = request_data.get('access_token')

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={access_token}"

    response = requests.get(url)
    data = response.json()

    if 'data' not in data:
        return jsonify({"error": "No data found"})
    # 获取每页数据量和需要查找的页数
    page_size = request_data.get('page_size', 10)  # 默认每页显示10条数据
    page_number = request_data.get('page_number', 1)  # 默认显示第1页

    # 计算起始索引和结束索引
    start_index = (page_number - 1) * page_size
    end_index = start_index + page_size

    # 截取相应页数的openid数据
    openid_list = data['data']['openid'][start_index:end_index]

    # 构建返回的JSON数据
    result = {
        "total": data['total'],  # 总数不变
        "count": len(openid_list),  # 返回的数据量
        "data": {
            "openid": openid_list
        },
        "next_openid": data['next_openid']  # 下一个openid
    }

    return jsonify(result)


# 标签管理模块
# 获取公众号已创建的标签
# @gongzhonghao_blueprint.route('/getyichuangjian', methods=['POST'])
# def getyichuangjian():
#
#
#     #     # 从请求中获取JSON数据
#     request_data = request.json
#
# #     # 获取access_token
#     access_token = request_data.get('access_token')
#
#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/tags/get?access_token={access_token}"
#
#     try:
#         # 发送POST请求到微信API
#         response = requests.get(url)
#
#         # 解析响应数据
#         result = response.json()
#
#         # 返回响应
#         return jsonify(result)
#
#     except Exception as e:
#         # 发生异常时返回错误信息
#         error_message = {"error": str(e)}
#         return jsonify(error_message), 500


# 获取标签下粉丝列表
@gongzhonghao_blueprint.route('/getTagUsers', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'G')
def getTagUsers():
    request_data = request.json
    request_data1 = request_data.pop('access_token', None)

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token={request_data1}"

    try:
        headers = {
            'Content-Type': 'application/json'
        }
        # 发送POST请求到微信API
        response = requests.post(url, headers=headers, data=json.dumps(request_data))

        # 解析响应数据
        result = response.json()

        # 返回响应
        return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# 批量为用户打标签
@gongzhonghao_blueprint.route('/TagUser1', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'G')
def TagUser1():
    request_data = request.json
    request_data1 = request_data.pop('access_token', None)

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={request_data1}"

    try:
        headers = {
            'Content-Type': 'application/json'
        }
        # 发送POST请求到微信API
        response = requests.post(url, headers=headers, data=json.dumps(request_data))

        # 解析响应数据
        result = response.json()

        # 返回响应
        return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# 批量为用户取消标签
@gongzhonghao_blueprint.route('/TagUser2', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'G')
def TagUser2():
    request_data = request.json
    request_data1 = request_data.pop('access_token', None)

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={request_data1}"

    try:
        headers = {
            'Content-Type': 'application/json'
        }
        # 发送POST请求到微信API
        response = requests.post(url, headers=headers, data=json.dumps(request_data))

        # 解析响应数据
        result = response.json()

        # 返回响应
        return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# 获取用户身上标签列表
@gongzhonghao_blueprint.route('/getTag', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'G')
def getTag():
    request_data = request.json
    request_data1 = request_data.pop('access_token', None)

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token={request_data1}"

    try:
        headers = {
            'Content-Type': 'application/json'
        }
        # 发送POST请求到微信API
        response = requests.post(url, headers=headers, data=json.dumps(request_data))

        # 解析响应数据
        result = response.json()

        # 返回响应
        return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# 用户管理模块
# 获取用户在同意授权时的token
@gongzhonghao_blueprint.route('/get_user_token', methods=['GET'])
def get_user_token():
    # 给吴燕使用的账号密码
    appid = "wxad55c42c5def12db"
    appsecret = "4c432ccecfcab9739cc402ccd6fce302"
    # 获取重定向后的code和state参数
    code = request.args.get('code')
    state = request.args.get('state')

    # 使用code换取access_token
    access_token_url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={appsecret}&code={code}&grant_type=authorization_code"
    response = requests.get(access_token_url)
    access_token_data = response.json()

    # 这里可以根据需要处理access_token_data，比如提取access_token等信息
    access_token = access_token_data.get('access_token')

    # 返回access_token或进行其他处理
    # return access_token

    # 这里可以更改（返回完整json数据）
    return access_token_data


# 获取用户信息
@gongzhonghao_blueprint.route('/get_user_info', methods=['GET'])
def get_user_info():
    # 提取access_token和openid
    access_token = request.args.get('access_token')
    openid = request.args.get('openid')

    # 拉取用户信息
    user_info_url = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN"
    user_info_response = requests.get(user_info_url)
    user_info_data = user_info_response.json()

    return user_info_data


# 合并接口
@gongzhonghao_blueprint.route('/get_user_infoall', methods=['GET'])
def get_user_infoall():
    # 给吴燕使用的账号密码
    appid = "wxad55c42c5def12db"
    appsecret = "4c432ccecfcab9739cc402ccd6fce302"
    # 获取重定向后的code和state参数
    code = request.args.get('code')
    state = request.args.get('state')

    # 使用code换取access_token
    access_token_url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={appsecret}&code={code}&grant_type=authorization_code"
    response = requests.get(access_token_url)
    access_token_data = response.json()

    # 这里可以根据需要处理access_token_data，比如提取access_token等信息
    access_token = access_token_data.get('access_token')
    openid = access_token_data.get('openid')

    # 拉取用户信息
    user_info_url = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN"
    user_info_response = requests.get(user_info_url)
    user_info_data = user_info_response.json()

    # 插入到用户表中
    openid = user_info_data['openid']
    nickname = user_info_data['nickname']
    headimgurl = user_info_data['headimgurl']
    print(user_info_data)
    db = None
    try:
        db = exts.get_db_gzh()
        if db:
            try:
                db = exts.get_db_gzh()
                cursor = db.cursor()
                sql_s = 'select * from users where openid=?'
                cursor.execute(sql_s, (openid,))
                if cursor.fetchall():
                    sql_updata = 'update users set nickname=?,headimgurl=? where openid=?'
                    cursor.execute(sql_updata, (nickname, headimgurl, openid,))
                    db.commit()
                    return jsonify({
                        "code": 200,
                        "status": "success",
                        "message": f"({nickname})用户添加成功",
                        "data": user_info_data}), 200
                sql_i = 'insert into users values(?,?,?)'
                cursor.execute(sql_i, (openid, nickname, headimgurl,))
                db.commit()
                return jsonify({
                    "code": 200,
                    "status": "success",
                    "message": f"({nickname})用户添加成功",
                    "data": user_info_data}), 200
            except sqlite3.Error as e:
                db.rollback()
                return jsonify({
                    "code": 500,
                    "status": "error",
                    "data": user_info_data,
                    "message": f"({nickname})用户添加失败:{str(e)}"
                }), 500
        else:
            return jsonify({
                "code": 500,
                "status": "error",
                "data": user_info_data,
                "message": "无法连接到数据库"
            }), 500
    except sqlite3.Error as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "data": user_info_data,
            "message": f"数据库操作出错: {str(e)}"
        }), 500
    finally:
        if db:
            db.close()

    # return user_info_data


# 模板消息模块
# 获取设置的行业信息
@gongzhonghao_blueprint.route('/getmodeinfo', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'K')
def getmodeinfo():
    #     # 从请求中获取JSON数据
    request_data = request.json

    #     # 获取access_token
    access_token = request_data.get('access_token')

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token={access_token}"

    try:
        # 发送POST请求到微信API
        response = requests.get(url)

        # 解析响应数据
        result = response.json()

        # 返回响应
        return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# 获取模板列表
@gongzhonghao_blueprint.route('/getmode', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'K')
def getmode():
    #     # 从请求中获取JSON数据
    request_data = request.json

    #     # 获取access_token
    access_token = request_data.get('access_token')

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={access_token}"

    try:
        # 发送POST请求到微信API
        response = requests.get(url)

        # 解析响应数据
        result = response.json()

        # 返回响应
        return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# 获取模板ID
@gongzhonghao_blueprint.route('/getmodeID', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'K')
def getmodeID():
    #     # 从请求中获取JSON数据
    request_data = request.json

    #     # 获取access_token
    access_token = request_data.get('access_token')

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={access_token}"

    try:
        headers = {
            'Content-Type': 'application/json'
        }
        # 发送POST请求到微信API
        # response = requests.post(url,headers=headers, data=json.dumps(data))

        # 解析响应数据
        # result = response.json()

        # 返回响应
        # return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# 发送消息
@gongzhonghao_blueprint.route('/sendmode', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'K')
def sendmode():
    #     # 从请求中获取JSON数据
    request_data = request.json
    request_data1 = request_data.pop('access_token', None)
    # return request_data

    #     # 获取access_token
    # access_token = request_data1.get('access_token')

    # 构建请求URL
    url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={request_data1}"
    # url = f"https://api.weixin.qq.com/cgi-bin/message/te"
    try:
        # 发送POST请求到微信API
        # response = requests.post(url,json=request_data1)
        headers = {
            'Content-Type': 'application/json'
        }
        # 发送POST请求到微信API
        response = requests.post(url, headers=headers, data=json.dumps(request_data))

        # 解析响应数据
        result = response.json()

        # 返回响应
        return jsonify(result)

    except Exception as e:
        # 发生异常时返回错误信息
        error_message = {"error": str(e)}
        return jsonify(error_message), 500


# # 创建标签
# @gongzhonghao_blueprint.route('/create_wechat_tag', methods=['POST'])
# def create_wechat_tag():

#     # 请求应该形如：http://baidu.com/path?access_token=123456

#     # 从请求中获取JSON数据
#     request_data = request.json

#     # 获取access_token
#     access_token = request.args.get('access_token')

#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/tags/create?access_token={access_token}"

#     try:
#         # 发送POST请求到微信API
#         response = requests.post(url, json=request_data)

#         # 解析响应数据
#         result = response.json()

#         # 返回响应
#         return jsonify(result), response.status_code

#     except Exception as e:
#         # 发生异常时返回错误信息
#         error_message = {"error": str(e)}
#         return jsonify(error_message), 500


# # 获取标签
# @gongzhonghao_blueprint.route('/get_wechat_tags', methods=['GET'])
# def get_wechat_tags():
#     global access_token  # 使用全局变量
#      # 请求应该形如：get_wechat_tags?access_token=your_access_token
#     if access_token != None:
#         pass
#     else:
#         access_token = request.args.get('access_token')


#     if access_token:
#         url = f"https://api.weixin.qq.com/cgi-bin/tags/get?access_token={access_token}"
#         try:
#             response = requests.get(url)
#             if response.status_code == 200:
#                 tags = response.json()
#                 return jsonify(tags)
#             else:
#                 return jsonify({"error": "Failed to retrieve WeChat tags."}), response.status_code
#         except Exception as e:
#             return jsonify({"error": f"Error: {e}"}), 500
#     else:
#         return jsonify({"error": "Missing access_token parameter."}), 400

# # 编辑标签
# @gongzhonghao_blueprint.route('/edit_wechat_tag', methods=['POST'])
# def create_wechat_tag():

#     # 从请求中获取JSON数据
#     request_data = request.json

#     # 获取access_token
#     access_token = request.args.get('access_token')

#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/tags/update?access_token={access_token}"

#     try:
#         # 发送POST请求到微信API
#         response = requests.post(url, json=request_data)

#         # 解析响应数据
#         result = response.json()

#         # 返回响应
#         return jsonify(result), response.status_code

#     except Exception as e:
#         # 发生异常时返回错误信息
#         error_message = {"error": str(e)}
#         return jsonify(error_message), 500

# # 删除标签
# @gongzhonghao_blueprint.route('/delete_wechat_tag', methods=['POST'])
# def create_wechat_tag():

#     # 从请求中获取JSON数据
#     request_data = request.json

#     # 获取access_token
#     access_token = request.args.get('access_token')

#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={access_token}"

#     try:
#         # 发送POST请求到微信API
#         response = requests.post(url, json=request_data)

#         # 解析响应数据
#         result = response.json()

#         # 返回响应
#         return jsonify(result), response.status_code

#     except Exception as e:
#         # 发生异常时返回错误信息
#         error_message = {"error": str(e)}
#         return jsonify(error_message), 500


# # 批量为用户打标签  （最多20个标签）
# @gongzhonghao_blueprint.route('/batch_wechat_tag', methods=['POST'])
# def create_wechat_tag():

#     # 从请求中获取JSON数据
#     request_data = request.json

#     # 获取access_token
#     access_token = request.args.get('access_token')

#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={access_token}"

#     try:
#         # 发送POST请求到微信API
#         response = requests.post(url, json=request_data)

#         # 解析响应数据
#         result = response.json()

#         # 返回响应
#         return jsonify(result), response.status_code

#     except Exception as e:
#         # 发生异常时返回错误信息
#         error_message = {"error": str(e)}
#         return jsonify(error_message), 500


# # 批量为用户取消标签
# @gongzhonghao_blueprint.route('/batchdelete_wechat_tag', methods=['POST'])
# def create_wechat_tag():

#     # 从请求中获取JSON数据
#     request_data = request.json

#     # 获取access_token
#     access_token = request.args.get('access_token')

#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={access_token}"

#     try:
#         # 发送POST请求到微信API
#         response = requests.post(url, json=request_data)

#         # 解析响应数据
#         result = response.json()

#         # 返回响应
#         return jsonify(result), response.status_code

#     except Exception as e:
#         # 发生异常时返回错误信息
#         error_message = {"error": str(e)}
#         return jsonify(error_message), 500


# # 获取用户身上的标签列表
# @gongzhonghao_blueprint.route('/getlabel_wechat_tag', methods=['POST'])
# def create_wechat_tag():

#     # 从请求中获取JSON数据
#     request_data = request.json

#     # 获取access_token
#     access_token = request.args.get('access_token')

#     # 构建请求URL
#     url = f"https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token={access_token}"

#     try:
#         # 发送POST请求到微信API
#         response = requests.post(url, json=request_data)

#         # 解析响应数据
#         result = response.json()

#         # 返回响应
#         return jsonify(result), response.status_code

#     except Exception as e:
#         # 发生异常时返回错误信息
#         error_message = {"error": str(e)}
#         return jsonify(error_message), 500


#吴燕需要的mian函数
@gongzhonghao_blueprint.route('/<pic_name>', methods=['POST', 'GET'])
def returnPictureExample(pic_name):
    pic_name = "static/gongzhonghao-files/" + pic_name
    return send_file(pic_name, mimetype='image/gif')


# 重定向实现
@gongzhonghao_blueprint.route('/test1')
def redirect_print_to_file():
    # 重定向 print 输出到 txt 文件
    with open('outputtryfirst.txt', 'a') as f:
        sys.stdout = f  # 将 print 输出重定向到 txt 文件
        print("Hello, world!")
        print("This is a test.")
        sys.stdout = sys.__stdout__  # 恢复标准输出

    # 读取 txt 文件内容
    with open('outputtryfirst.txt', 'r') as f:
        file_content = f.read()

    # 返回 txt 文件内容作为响应
    return file_content


# # 添加标签
@gongzhonghao_blueprint.route('/tag/addTag', methods=['POST'], endpoint='add_tag_endpoint')
@jwt_required()
@exts.permission_required('gongzhonghao', 'G')
def getyichuangjian():
    tagid = request.json.get('tagid', None)
    name = request.json.get('name', None)
    if not tagid or not name:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "缺少必要参数",
            "details": "请您检查tagid和name是否输入正确"
        }), 400
    db = None
    try:
        db = exts.get_db_gzh()
        if db:
            try:
                db = exts.get_db_gzh()
                cursor = db.cursor()
                sql_s = 'select * from tag where tagid=?'
                cursor.execute(sql_s, (tagid,))
                if cursor.fetchall():
                    return jsonify({
                        "code": 500,
                        "status": "error",
                        "message": f"您要插入的（{name}）标签已存在，如有修改请手动修改或者删除重新插入"})
                sql_i = 'insert into tag(tagid,name) values(?,?)'
                cursor.execute(sql_i, (tagid, name,))
                db.commit()
                return jsonify({
                    "code": 200,
                    "status": "success",
                    "message": f"({name})标签添加成功",
                    "data": request.json}), 200
            except sqlite3.Error as e:
                db.rollback()
                return jsonify({
                    "code": 500,
                    "status": "error",
                    "message": f"({name})标签添加失败:{str(e)}"
                }), 500
        else:
            return jsonify({
                "code": 500,
                "status": "error",
                "message": "无法连接到数据库"
            }), 500
    except sqlite3.Error as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": f"数据库操作出错: {str(e)}"
        }), 500
    finally:
        if db:
            db.close()


# 删除标签
@gongzhonghao_blueprint.route('/tag/deleteTag/<tagid>', methods=['DELETE'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'G')
def delete_tag(tagid):
    tagid = int(tagid)
    if not isinstance(tagid, int):
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "未提供有效的tagID"
        }), 400
    conn = None
    try:
        conn = exts.get_db_gzh()
        cur = conn.cursor()
        result = []
        sql = 'DELETE FROM tag WHERE tagid = ?'
        cur.execute(sql, (tagid,))
        if cur.rowcount == 0:
            result.append({
                'tagid': tagid,
                'status': 'error',
                'message': '未找到标签信息'
            })
        else:
            result.append({
                'tagid': tagid,
                'status': 'success',
                'message': '删除标签信息成功'
            })
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "操作成功",
            "data": result
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": f"错误详情：{e}"
        }), 500
    finally:
        if conn:
            conn.close()


# 查询标签
@gongzhonghao_blueprint.route('/getyichuangjian', methods=['GET'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'G')
def get_tag():
    id = request.args.get('id', None)
    tagid = request.args.get('tagid', None)
    name = request.args.get('name', None)
    # page = request.args.get('page', 1)
    # page_size = request.args.get('page_size', 10)
    # if page < 1 or page_size < 1:
    #     return jsonify({
    #         "code": 400,
    #         "status": "error",
    #         "message": "请求参数错误",
    #         "details": "page 和 page_size 必须为正整数"
    #     }), 400
    sql = 'SELECT * FROM tag'
    conditions = []
    params = []

    if name:
        conditions.append('name LIKE ?')
        params.append("%" + name + "%")

    if tagid:
        conditions.append('tagid=?')
        params.append(tagid)

    if id:
        conditions.append('id=?')
        params.append(id)

    if conditions:
        sql += ' WHERE ' + ' AND '.join(conditions)

    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 查询当前页数据
        if not id and not tagid and not name:
            cursor.execute(sql)
        else:
            print(sql)
            # print(factor)
            cursor.execute(sql, params)
        results = cursor.fetchall()
        cursor.close()
        if not results:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "未找到符合条件的标签信息"
            }), 404
        results = [dict(zip([column[0] for column in cursor.description], row)) for row in results]
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "查询成功",
            "data": {
                "total_records": len(results),
                "results": results
            }
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 查询用户
@gongzhonghao_blueprint.route('/users/get', methods=['GET'], endpoint='users')
@jwt_required()
@exts.permission_required('gongzhonghao', 'J')
def get_tag():
    openid = request.args.get('openid', None)
    nickname = request.args.get('nickname', None)
    # headimgurl = request.args.get('headimgurl',None)
    sql = 'SELECT * FROM users'
    conditions = []
    params = []

    if nickname:
        conditions.append('nickname LIKE ?')
        params.append("%" + nickname + "%")

    if openid:
        conditions.append('openid=?')
        params.append(openid)

    if conditions:
        sql += ' WHERE ' + ' AND '.join(conditions)

    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 查询当前页数据
        if not id and not openid and not nickname:
            cursor.execute(sql)
        else:
            print(sql)
            cursor.execute(sql, params)
        results = cursor.fetchall()
        cursor.close()
        if not results:
            return jsonify({
                "code": 200,
                "status": "success",
                "message": "查询成功",
                "data": {
                    "total_records": 0,
                    "results": []
                }
            }), 200
        results = [dict(zip([column[0] for column in cursor.description], row)) for row in results]
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "查询成功",
            "data": {
                "total_records": len(results),
                "results": results
            }
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 公众号自动回复
@gongzhonghao_blueprint.route('/wechat', methods=['GET', 'POST'])
def wechat():
    if request.method == 'GET':
        # 验证服务器配置
        signature = request.args.get('signature', '')
        timestamp = request.args.get('timestamp', '')
        nonce = request.args.get('nonce', '')
        echostr = request.args.get('echostr', '')
        try:
            check_signature(WECHAT_TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            abort(403)
        return echostr
    else:
        # 解析消息
        try:
            xml_data = request.data
            msg = parse_message(xml_data)
            conn = exts.get_db_gzh()
            cursor = conn.cursor()
        except Exception as e:
            print(f"Error parsing message or connecting to DB: {e}")
            abort(500)

        # 判断token是否存在或者是否过期
        global access_token, expires_time
        try:
            if time.time() > expires_time or not access_token:
                access_token, expires_time = exts.fetch_wechat_access_token("wxad55c42c5def12db",
                                                                            "4c432ccecfcab9739cc402ccd6fce302")
        except Exception as e:
            print(f"Error getting access token: {e}")
            abort(500)

        # 判断消息类型
        if msg.type == 'text':
            try:
                sql = "SELECT rule_id, rule_name, reply_method FROM rules WHERE status = 'active'"
                cursor.execute(sql)
                rules = cursor.fetchall()
                matched = False
                responses = []
                # 遍历所有有效规则
                for rule in rules:
                    rule_id = rule["rule_id"]
                    reply_method = rule["reply_method"]
                    sql = ("SELECT trigger_value, match_rule FROM trigger_conditions WHERE rule_id = ? AND "
                           "trigger_type = 'keyword'")
                    cursor.execute(sql, (rule_id,))
                    trigger_conditions = cursor.fetchall()
                    # 遍历所有关键词触发条件
                    for trigger_condition in trigger_conditions:
                        # 判断匹配规则
                        if trigger_condition["match_rule"] == "exact":
                            if msg.content == trigger_condition["trigger_value"]:
                                matched = True
                        elif trigger_condition["match_rule"] == "fuzzy":
                            if trigger_condition["trigger_value"] in msg.content:
                                matched = True
                        # 如果匹配成功，获取回复内容
                        if matched:
                            sql = "SELECT reply_type, reply_content FROM replies WHERE rule_id = ?"
                            cursor.execute(sql, (rule_id,))
                            responses.extend(cursor.fetchall())
                            break  # 关键词匹配成功后跳出循环
                    # 如果匹配成功，根据回复方式返回消息
                    if matched:
                        if reply_method == 'random':
                            response = random.choice(responses)
                            return exts.handle_reply(response, msg, access_token)
                        elif reply_method == 'all':
                            return exts.handle_all_replies(responses, msg, access_token)
                # 如果没有匹配到任何关键词，返回提示现有关键词
                if not matched:
                    sql = """
                    SELECT rules.rule_name, trigger_conditions.trigger_value 
                    FROM trigger_conditions 
                    JOIN rules ON trigger_conditions.rule_id = rules.rule_id 
                    WHERE trigger_conditions.trigger_type = 'keyword' AND rules.status = 'active'
                    """
                    cursor.execute(sql)
                    keywords = cursor.fetchall()
                    keyword_dict = {}
                    for kw in keywords:
                        rule_name = kw['rule_name']
                        trigger_value = kw['trigger_value']
                        if rule_name not in keyword_dict:
                            keyword_dict[rule_name] = []
                        keyword_dict[rule_name].append(trigger_value)
                    # 拼接关键词字符串
                    keyword_str = "\n".join([f"{rule}: {', '.join(vals)}" for rule, vals in keyword_dict.items()])
                    reply = TextReply(content=f"当前支持的关键词有：\n{keyword_str}", message=msg)
                    return reply.render()

            except Exception as e:
                print(f"Error processing text message: {e}")
                abort(500)

        elif msg.type == 'event':
            if msg.event == 'subscribe':
                try:
                    # 查询订阅触发的规则和回复方式
                    sql = """
                    SELECT rules.rule_id, rules.reply_method 
                    FROM rules
                    JOIN trigger_conditions
                    ON rules.rule_id = trigger_conditions.rule_id
                    WHERE trigger_conditions.trigger_type = 'subscribe'
                    AND rules.status = 'active'
                    """
                    cursor.execute(sql)
                    rule = cursor.fetchone()
                    # 如果有订阅触发的规则，根据回复方式返回消息
                    if rule:
                        rule_id = rule["rule_id"]
                        reply_method = rule["reply_method"]
                        sql = "SELECT reply_type, reply_content FROM replies WHERE rule_id = ?"
                        cursor.execute(sql, (rule_id,))
                        responses = cursor.fetchall()
                        # 根据回复方式返回消息
                        if reply_method == 'random':
                            response = random.choice(responses)
                            return exts.handle_reply(response, msg, access_token)
                        elif reply_method == 'all':
                            return exts.handle_all_replies(responses, msg, access_token)

                except Exception as e:
                    print(f"Error processing subscribe event: {e}")
                    abort(500)

        return "success"


# 关键词回复规则新增
@gongzhonghao_blueprint.route('/keywords/add', methods=['POST'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def add_keyword_rule():
    rule_name = request.form.get('rule_name', None)
    reply_method = request.form.get('reply_method', None)
    status = request.form.get('status', 'active')
    keywords_str = request.form.get('keywords', None)
    replies_str = request.form.get('replies', None)
    pictures = request.files.getlist('pictures')
    if not rule_name or not reply_method or not keywords_str or not replies_str:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "缺少必要参数",
            "details": "请您检查rule_name、reply_method、keywords和replies是否输入正确"
        }), 400
    # 检查keywords和replies是否为json格式
    try:
        keywords = json.loads(keywords_str)
        replies = json.loads(replies_str)
    except json.JSONDecodeError as e:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "参数格式错误",
            "details": "请您检查keywords和replies是否为json列表格式, 且已经转换为字符串"
        }), 400
    # 判断token是否存在或者是否过期
    global access_token, expires_time
    try:
        if time.time() > expires_time or not access_token:
            access_token, expires_time = exts.fetch_wechat_access_token("wxad55c42c5def12db",
                                                                        "4c432ccecfcab9739cc402ccd6fce302")
    except Exception as e:
        print(f"Error getting access token: {e}")
        abort(500)
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 上传图片到微信服务器获取media_id
        picture_media_ids = {}
        if pictures:
            for picture in pictures:
                sql = "SELECT media_id, url FROM images WHERE name = ?"
                cursor.execute(sql, (picture.filename,))
                result = cursor.fetchone()
                if result:
                    picture_media_ids[picture.filename] = {
                        "media_id": result["media_id"],
                        "url": result["url"]
                    }
                else:
                    media_temp = exts.upload_image_to_wechat(access_token, picture)
                    if media_temp:
                        ad = f"static/gongzhonghao-files/images/{picture.filename}"
                        url = exts.DOMAIN + ad
                        os.makedirs(os.path.dirname(ad), exist_ok=True)
                        picture.seek(0)  # 确保文件指针在文件的开头
                        with open(ad, 'wb') as f:
                            f.write(picture.read())
                        sql = "INSERT INTO images (name, media_id, url) VALUES (?, ?, ?)"
                        cursor.execute(sql, (picture.filename, media_temp["media_id"], url))
                        picture_media_ids[picture.filename] = {
                            "media_id": media_temp["media_id"],
                            "url": url
                        }
                    else:
                        picture_media_ids[picture.filename] = media_temp
        # 插入规则
        sql = "INSERT INTO rules (rule_name, reply_method, status) VALUES (?, ?, ?)"
        cursor.execute(sql, (rule_name, reply_method, status))
        rule_id = cursor.lastrowid
        # 插入关键词触发条件
        for keyword in keywords:
            sql = ("INSERT INTO trigger_conditions (rule_id, trigger_type, trigger_value, match_rule)"
                   " VALUES (?, ?, ?, ?)")
            cursor.execute(sql, (rule_id, 'keyword', keyword["keyword"], keyword["match_type"]))
        # 插入回复
        for reply in replies:
            if reply["reply_type"] == 'text':
                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (rule_id, 'text', reply["reply_value"]))
            elif reply["reply_type"] == 'image':
                picture = reply["reply_value"]["picture"]
                reply_content = picture_media_ids[picture]
                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (rule_id, 'image',  json.dumps(reply_content)))
            elif reply["reply_type"] == 'miniprogram':
                picture = reply["reply_value"]["picture"]
                reply_content = {
                    "app_id": reply["reply_value"]["app_id"],
                    "page_path": reply["reply_value"]["page_path"],
                    "title": reply["reply_value"]["title"],
                    "thumb_media_id": picture_media_ids[picture]["media_id"],
                    "thumb_url": picture_media_ids[picture]["url"],
                    }
                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (rule_id, 'miniprogram',  json.dumps(reply_content)))
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "规则添加成功",
            "data": {
                "rule_id": rule_id,
                "rule_name": rule_name
            }
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 关键词回复规则修改
@gongzhonghao_blueprint.route('/keywords/update/<rule_id>', methods=['PUT'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def update_keyword_rule(rule_id):
    rule_name = request.form.get('rule_name', None)
    reply_method = request.form.get('reply_method', None)
    status = request.form.get('status', 'active')
    keywords_str = request.form.get('keywords', None)
    replies_str = request.form.get('replies', None)
    pictures = request.files.getlist('pictures')
    if not rule_name or not reply_method or not keywords_str or not replies_str:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "缺少必要参数",
            "details": "请您检查rule_name、reply_method、keywords和replies是否输入正确"
        }), 400
    # 检查keywords和replies是否为json格式
    try:
        keywords = json.loads(keywords_str)
        replies = json.loads(replies_str)
    except json.JSONDecodeError as e:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "参数格式错误",
            "details": "请您检查keywords和replies是否为json列表格式, 且已经转换为字符串"
        }), 400
    # 判断token是否存在或者是否过期
    global access_token, expires_time
    try:
        if time.time() > expires_time or not access_token:
            access_token, expires_time = exts.fetch_wechat_access_token("wxad55c42c5def12db",
                                                                        "4c432ccecfcab9739cc402ccd6fce302")
    except Exception as e:
        print(f"Error getting access token: {e}")
        abort(500)
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 上传图片到微信服务器获取media_id
        picture_media_ids = {}
        if pictures:
            for picture in pictures:
                sql = "SELECT media_id, url FROM images WHERE name = ?"
                cursor.execute(sql, (picture.filename,))
                result = cursor.fetchone()
                if result:
                    picture_media_ids[picture.filename] = {
                        "media_id": result["media_id"],
                        "url": result["url"]
                    }
                else:
                    media_temp = exts.upload_image_to_wechat(access_token, picture)
                    if media_temp:
                        ad = f"static/gongzhonghao-files/images/{picture.filename}"
                        url = exts.DOMAIN + ad
                        os.makedirs(os.path.dirname(ad), exist_ok=True)
                        picture.seek(0)  # 确保文件指针在文件的开头
                        with open(ad, 'wb') as f:
                            f.write(picture.read())
                        sql = "INSERT INTO images (name, media_id, url) VALUES (?, ?, ?)"
                        cursor.execute(sql, (picture.filename, media_temp["media_id"], url))
                        picture_media_ids[picture.filename] = {
                            "media_id": media_temp["media_id"],
                            "url": url
                        }
                    else:
                        picture_media_ids[picture.filename] = media_temp
        # 更新规则
        sql = "UPDATE rules SET rule_name = ?, reply_method = ?, status = ? WHERE rule_id = ?"
        cursor.execute(sql, (rule_name, reply_method, status, rule_id))
        # 删除原有关键词触发条件
        sql = "DELETE FROM trigger_conditions WHERE rule_id = ? AND trigger_type = 'keyword'"
        cursor.execute(sql, (rule_id,))
        # 插入新的关键词触发条件
        for keyword in keywords:
            sql = ("INSERT INTO trigger_conditions (rule_id, trigger_type, trigger_value, match_rule)"
                   " VALUES (?, ?, ?, ?)")
            cursor.execute(sql, (rule_id, 'keyword', keyword["keyword"], keyword["match_type"]))
        # 删除原有回复
        sql = "DELETE FROM replies WHERE rule_id = ?"
        cursor.execute(sql, (rule_id,))
        # 插入新的回复
        for reply in replies:
            if reply["reply_type"] == 'text':
                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (rule_id, 'text', reply["reply_value"]))
            elif reply["reply_type"] == 'image':
                reply_content = reply["reply_value"]
                if "picture" in reply_content and reply_content["picture"]:
                    picture = reply_content["picture"]
                    if picture in picture_media_ids:
                        reply_content = picture_media_ids[picture]
                    else:
                        # 如果找不到对应的 media_id，保留原始的 reply_content
                        reply_content.pop("picture", None)
                else:
                    # 如果没有 picture 字段或为空，移除它
                    reply_content.pop("picture", None)

                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (rule_id, 'image', json.dumps(reply_content)))
            elif reply["reply_type"] == 'miniprogram':
                reply_content = reply["reply_value"]
                if "picture" in reply_content and reply_content["picture"]:
                    picture = reply_content["picture"]
                    if picture in picture_media_ids:
                        reply_content.update({
                            "thumb_media_id": picture_media_ids[picture]["media_id"],
                            "thumb_url": picture_media_ids[picture]["url"],
                        })
                    # 无论是否找到对应的 media_id，都移除 picture 字段
                    reply_content.pop("picture", None)
                else:
                    # 如果没有 picture 字段或为空，移除它
                    reply_content.pop("picture", None)

                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (rule_id, 'miniprogram', json.dumps(reply_content)))

        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "规则更新成功",
            "data": {
                "rule_id": rule_id,
                "rule_name": rule_name
            }
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 关键词回复规则查询
@gongzhonghao_blueprint.route('/keywords/query', methods=['GET'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def query_keyword_rule():
    rule_name = request.args.get('rule_name', None)
    keyword = request.args.get('keyword', None)
    where_clause = []
    params = []
    if rule_name:
        where_clause.append("r.rule_name LIKE ?")
        params.append(f"%{rule_name}%")
    if keyword:
        where_clause.append("tc.trigger_value LIKE ?")
        params.append(f"%{keyword}%")
    where_clause = " WHERE " + " AND ".join(where_clause) if where_clause else ""
    where_clause += " AND tc.trigger_type = 'keyword' ORDER BY r.rule_id DESC"
    sql = """
    SELECT DISTINCT r.rule_id, r.rule_name, r.reply_method, r.status
    FROM rules r
    JOIN trigger_conditions tc ON r.rule_id = tc.rule_id
    """
    sql += where_clause
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        cursor.execute(sql, tuple(params))
        results = cursor.fetchall()
        if not results:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "未找到符合条件的规则信息"
            }), 404

        # 为每个规则添加关键词和回复类型详细信息
        enriched_results = []
        for result in results:
            rule_id = result["rule_id"]
            result_dict = dict(result)
            result_dict["reply_method"] = "随机" if result_dict["reply_method"] == "random" else "全部"
            result_dict["status"] = "已启用" if result_dict["status"] == "active" else "未启用"
            # 获取关键词
            cursor.execute(
                "SELECT trigger_value FROM trigger_conditions WHERE rule_id = ? AND trigger_type = 'keyword'",
                (rule_id,))
            keywords = cursor.fetchall()
            result_dict["keywords"] = ", ".join(
                [f"{index + 1}:{kw['trigger_value']}" for index, kw in enumerate(keywords)])

            # 获取回复类型
            cursor.execute("SELECT reply_type FROM replies WHERE rule_id = ?", (rule_id,))
            reply_types = cursor.fetchall()
            reply_types_formatted = ", ".join(
                [f"{index + 1}:{rt['reply_type']}" for index, rt in enumerate(reply_types)])
            result_dict["reply_types"] = reply_types_formatted.replace("text", "文本").replace("image", "图片").replace(
                "miniprogram", "小程序")

            enriched_results.append(result_dict)

        return jsonify({
            "code": 200,
            "status": "success",
            "message": "查询成功",
            "data": {
                "total_records": len(enriched_results),
                "results": enriched_results
            }
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 获取关键词回复规则详情
@gongzhonghao_blueprint.route('/keywords/<rule_id>', methods=['GET'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def get_keyword_rule_detail(rule_id):
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 查询规则信息
        cursor.execute("SELECT * FROM rules WHERE rule_id = ?", (rule_id,))
        rule = cursor.fetchone()
        if not rule:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "未找到规则信息"
            }), 404
        rule_dict = dict(rule)
        # 查询关键词触发条件
        cursor.execute("SELECT trigger_value, match_rule FROM trigger_conditions WHERE rule_id = ?",
                       (rule_id,))
        keywords = cursor.fetchall()
        keywords = [dict(kw) for kw in keywords]
        for kw in keywords:
            kw["keyword"] = kw.pop("trigger_value")
            kw["match_type"] = kw.pop("match_rule")
        rule_dict["keywords"] = keywords
        # 查询回复
        cursor.execute("SELECT reply_type, reply_content FROM replies WHERE rule_id = ?", (rule_id,))
        replies = cursor.fetchall()
        replies = [dict(reply) for reply in replies]
        for reply in replies:
            reply["reply_type"] = reply.pop("reply_type")
            reply["reply_value"] = reply.pop("reply_content")
            if reply["reply_type"] == "text":
                reply["reply_value"] = reply["reply_value"]
            elif reply["reply_type"] == "image":
                reply["reply_value"] = json.loads(reply["reply_value"])
            elif reply["reply_type"] == "miniprogram":
                reply["reply_value"] = json.loads(reply["reply_value"])
        rule_dict["replies"] = replies
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "查询成功",
            "data": rule_dict
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 关键词回复规则状态修改
@gongzhonghao_blueprint.route('/keywords/status/<rule_id>', methods=['PATCH'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def update_keyword_rule_status(rule_id):
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 查询规则信息
        cursor.execute("SELECT status FROM rules WHERE rule_id = ?", (rule_id,))
        rule = cursor.fetchone()
        if not rule:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "未找到规则信息"
            }), 404
        status = "inactive" if rule["status"] == "active" else "active"
        cursor.execute("UPDATE rules SET status = ? WHERE rule_id = ?", (status, rule_id))
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "状态修改成功",
            "data": {
                "rule_id": rule_id,
                "status": status
            }
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


@gongzhonghao_blueprint.route('/keywords/delete/<rule_id>', methods=['DELETE'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def delete_keyword_rule(rule_id):
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()

        # 查询规则信息
        cursor.execute("SELECT * FROM rules WHERE rule_id = ?", (rule_id,))
        rule = cursor.fetchone()
        if not rule:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "未找到规则信息"
            }), 404
        # 判断token是否存在或者是否过期
        global access_token, expires_time
        try:
            if time.time() > expires_time or not access_token:
                access_token, expires_time = exts.fetch_wechat_access_token("wxad55c42c5def12db",
                                                                            "4c432ccecfcab9739cc402ccd6fce302")
        except Exception as e:
            print(f"Error getting access token: {e}")
            abort(500)
        # 删除相关的媒体文件
        exts.delete_media_files(cursor, rule_id, access_token)
        # 删除关键词
        cursor.execute("DELETE FROM trigger_conditions WHERE rule_id = ?", (rule_id,))
        # 删除回复
        cursor.execute("DELETE FROM replies WHERE rule_id = ?", (rule_id,))
        # 删除规则
        cursor.execute("DELETE FROM rules WHERE rule_id = ?", (rule_id,))
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "规则删除成功",
            "data": {
                "rule_id": rule_id
            }
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 关键词回复内容获取
@gongzhonghao_blueprint.route('/follow/query', methods=['GET'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def query_follow_reply():
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 查询规则信息
        cursor.execute("SELECT reply_method, status FROM rules WHERE rule_id = 1")
        rule = cursor.fetchone()
        rule_dict = dict(rule)
        # 查询回复
        cursor.execute("SELECT reply_type, reply_content FROM replies WHERE rule_id = 1")
        replies = cursor.fetchall()
        replies = [dict(reply) for reply in replies]
        for reply in replies:
            reply["reply_type"] = reply.pop("reply_type")
            reply["reply_value"] = reply.pop("reply_content")
            if reply["reply_type"] == "text":
                reply["reply_value"] = reply["reply_value"]
            elif reply["reply_type"] == "image":
                reply["reply_value"] = json.loads(reply["reply_value"])
            elif reply["reply_type"] == "miniprogram":
                reply["reply_value"] = json.loads(reply["reply_value"])
        rule_dict["replies"] = replies
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "查询成功",
            "data": rule_dict
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 关注后回复规则修改
@gongzhonghao_blueprint.route('/follow/update', methods=['PUT'])
@jwt_required()
@exts.permission_required('gongzhonghao', 'L')
def update_follow_reply():
    status = request.form.get('status', 'active')
    reply_method = request.form.get('reply_method', None)
    replies_str = request.form.get('replies', None)
    pictures = request.files.getlist('pictures')
    if not reply_method or not replies_str:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "缺少必要参数",
            "details": "请您检查reply_method和replies是否输入正确"
        }), 400
    # 检查replies是否为json格式
    try:
        replies = json.loads(replies_str)
    except json.JSONDecodeError as e:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "参数格式错误",
            "details": "请您检查replies是否为json列表格式, 且已经转换为字符串"
        }), 400
    # 判断token是否存在或者是否过期
    global access_token, expires_time
    try:
        if time.time() > expires_time or not access_token:
            access_token, expires_time = exts.fetch_wechat_access_token("wxad55c42c5def12db",
                                                                        "4c432ccecfcab9739cc402ccd6fce302")
    except Exception as e:
        print(f"Error getting access token: {e}")
        abort(500)
    conn = None
    try:
        conn = exts.get_db_gzh()
        cursor = conn.cursor()
        # 上传图片到微信服务器获取media_id
        picture_media_ids = {}
        if pictures:
            for picture in pictures:
                sql = "SELECT media_id, url FROM images WHERE name = ?"
                cursor.execute(sql, (picture.filename,))
                result = cursor.fetchone()
                if result:
                    picture_media_ids[picture.filename] = {
                        "media_id": result["media_id"],
                        "url": result["url"]
                    }
                else:
                    media_temp = exts.upload_image_to_wechat(access_token, picture)
                    if media_temp:
                        ad = f"static/gongzhonghao-files/images/{picture.filename}"
                        url = exts.DOMAIN + ad
                        os.makedirs(os.path.dirname(ad), exist_ok=True)
                        picture.seek(0)  # 确保文件指针在文件的开头
                        with open(ad, 'wb') as f:
                            f.write(picture.read())
                        sql = "INSERT INTO images (name, media_id, url) VALUES (?, ?, ?)"
                        cursor.execute(sql, (picture.filename, media_temp["media_id"], url))
                        picture_media_ids[picture.filename] = {
                            "media_id": media_temp["media_id"],
                            "url": url
                        }
                    else:
                        picture_media_ids[picture.filename] = media_temp
        # 更新规则
        sql = "UPDATE rules SET reply_method = ?, status = ? WHERE rule_id = 1"
        cursor.execute(sql, (reply_method, status))
        # 删除原有回复
        sql = "DELETE FROM replies WHERE rule_id = 1"
        cursor.execute(sql)
        # 插入新的回复
        for reply in replies:
            if reply["reply_type"] == 'text':
                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (1, 'text', reply["reply_value"]))
            elif reply["reply_type"] == 'image':
                reply_content = reply["reply_value"]
                if "picture" in reply_content and reply_content["picture"]:
                    picture = reply_content["picture"]
                    if picture in picture_media_ids:
                        reply_content = picture_media_ids[picture]
                    else:
                        # 如果找不到对应的 media_id，保留原始的 reply_content
                        reply_content.pop("picture", None)
                else:
                    # 如果没有 picture 字段或为空，移除它
                    reply_content.pop("picture", None)

                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (1, 'image', json.dumps(reply_content)))
            elif reply["reply_type"] == 'miniprogram':
                reply_content = reply["reply_value"]
                if "picture" in reply_content and reply_content["picture"]:
                    picture = reply_content["picture"]
                    if picture in picture_media_ids:
                        reply_content.update({
                            "thumb_media_id": picture_media_ids[picture]["media_id"],
                            "thumb_url": picture_media_ids[picture]["url"],
                        })
                    # 无论是否找到对应的 media_id，都移除 picture 字段
                    reply_content.pop("picture", None)
                else:
                    # 如果没有 picture 字段或为空，移除它
                    reply_content.pop("picture", None)

                sql = "INSERT INTO replies (rule_id, reply_type, reply_content) VALUES (?, ?, ?)"
                cursor.execute(sql, (1, 'miniprogram', json.dumps(reply_content)))

        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "规则更新成功",
            "data": {
                "rule_id": 1,
                "rule_name": "关注后回复"
            }
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()

